package com.akka.demo.actor;

import akka.actor.AbstractActor;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import com.akka.demo.model.*;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * Created by Administrator on 2018/2/26.
 * 设备
 */
@Component
@Scope("prototype")
public class Device extends AbstractActor {

    private LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this);

    final private String groupId;

    final private String deviceId;

    private double lastTemperatureReading;

    public Device(String groupId, String deviceId) {
        this.groupId = groupId;
        this.deviceId = deviceId;
    }

    public double getLastTemperatureReading() {
        return lastTemperatureReading;
    }

    public void setLastTemperatureReading(double lastTemperatureReading) {
        this.lastTemperatureReading = lastTemperatureReading;
    }

    @Override
    public void preStart() {
        log.info("Device actor {}-{} started", groupId, deviceId);
        setLastTemperatureReading(new Random().nextInt(40));
    }

    @Override
    public void postStop() {
        log.info("Device actor {}-{} stopped", groupId, deviceId);
    }

    @Override
    public Receive createReceive() {
        return receiveBuilder()
                .match(ReadTemperature.class, this::receiveReadTemperature)
                .match(RecordTemperature.class, this::receiveRecordTemperature)
                .match(DeviceManager.RequestTrackDevice.class, this::receiveRequestTrackDevice)
                .matchAny(this::receiveUnknownMsg)
                .build();
    }

    private void receiveReadTemperature(ReadTemperature readTemperature) {
        getSender().tell(new RespondTemperature(readTemperature.getRequestId(), getLastTemperatureReading()), getSelf());
    }

    private void receiveRecordTemperature(RecordTemperature recordTemperature) {
        log.info("Recorded temperature reading {} with {}", recordTemperature.getValue(), recordTemperature.getRequestId());
        setLastTemperatureReading(recordTemperature.getValue());
        getSender().tell(new TemperatureRecorded(recordTemperature.getRequestId()), getSelf());
    }

    private void receiveRequestTrackDevice(DeviceManager.RequestTrackDevice requestTrackDevice) {
        log.info("Device registered with groupId:{} and deviceId:{}", requestTrackDevice.getGroupId(), requestTrackDevice.getDeviceId());
        getSender().tell(new DeviceManager.DeviceRegistered(), getSelf());
    }

    private void receiveUnknownMsg(Object o) {
        log.info("received unknown message");
    }
}
